<template>
    <div>
        <el-skeleton v-if="editorLoading" :rows="5" animated class="flex-1" />
        <div class="mb-4 flex">
            <div class="flex-1">
                <div ref="editorRef" id="editorRef"></div>
            </div>
            <div
                v-if="!hideAI"
                class="max-h-[800px] w-[400px] pl-2"
                :class="{
                    'min-h-[400px]': !editorLoading,
                }"
            >
                <Chat
                    v-if="!editorLoading"
                    :getContextDescription="getContextDescription"
                    agent="writing"
                    helloMessage='你好，我是AI小助手，可以帮助你快速完成写作。尝试跟我说 "生成一篇关于XX的内容" 吧~'
                />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { IContextDescriptionItem } from '@/apis/chat/interfaces'
import { IResp } from '@/apis/interfaces'
import { IUploadResData } from '@/apis/upload'
import { getToken } from '@/utils/token'
import { ElMessage } from 'element-plus'
import VEditor from 'vditor'
import 'vditor/dist/index.css'
import { onMounted, ref, watch } from 'vue'
import Chat from './Chat/Chat.vue'
import { API_BASE_URL } from '@/utils/url'

const editorRef = ref<any>(null)
const editorLoading = ref(true)

let editor: InstanceType<typeof VEditor> | null = null

const props = defineProps<{
    modelValue: string
    hideAI?: boolean
}>()

const emit = defineEmits(['update:modelValue'])

onMounted(() => {
    // return
    // console.log(document.getElementById('editorRef'))
    setTimeout(() => {
        if (!editorRef.value) return
        editor = new VEditor(editorRef.value, {
            // height: 360,
            minHeight: 400,
            toolbarConfig: {
                pin: true,
            },
            upload: {
                url: `${API_BASE_URL}/upload`,
                headers: {
                    Authorization: `Bearer ${getToken()}`,
                },
                extraData: {
                    folder: 'article',
                },
                fieldName: 'file',
                format: (_file, responseText) => {
                    const res = JSON.parse(responseText) as IResp<
                        IUploadResData[]
                    >
                    if (!res.success) {
                        ElMessage.error('上传失败')
                        return '上传失败'
                    }
                    const succMap = {}
                    if (res.data) {
                        res.data.forEach((v) => {
                            succMap[v.originalFilename] = v.url
                        })
                    }
                    return JSON.stringify({
                        msg: '',
                        code: 0,
                        data: {
                            errFiles: [],
                            succMap: succMap,
                        },
                    })
                },
            },
            cache: {
                enable: false,
            },
            after() {
                console.log('after')
                editorLoading.value = false
                if (!editor) return
                editor.setValue(props.modelValue)
            },
            input: (value) => {
                emit('update:modelValue', value)
            },
            preview: {
                actions: [],
            },
        })
    }, 300)
})

const getContextDescription: () => IContextDescriptionItem[] = () => {
    return [
        {
            key: 'custom',
            value: '文章写作助手',
        },
    ]
}

watch(
    () => props.modelValue,
    (newVal) => {
        if (!editor || !editor.vditor) return
        const curr = editor.getValue()
        if (curr === newVal) return
        editor.setValue(newVal)
    }
)

defineExpose({
    editor,
})
</script>

<style scoped></style>
